<template>
  <div id="map_container" ref="mapContainer"></div>
</template>

<script setup>
import { onMounted, onUnmounted,watch,ref,computed } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

// 定义 props 接收坐标数据和站点名称
const props = defineProps({
  longitude: {
    type: Number,
    default: null
  },
  latitude: {
    type: Number,
    default: null
  },
  siteName: {
    type: String,
    default: '站点位置'
  },
  // 后端返回的分散经纬度属性（point11=经度, point12=纬度...）
  point11: { type: Number, default: 0 },
  point12: { type: Number, default: 0 },
  point21: { type: Number, default: 0 },
  point22: { type: Number, default: 0 },
  point31: { type: Number, default: 0 },
  point32: { type: Number, default: 0 },
  point41: { type: Number, default: 0 },
  point42: { type: Number, default: 0 },
  point51: { type: Number, default: 0 },
  point52: { type: Number, default: 0 },

  showDistrict: { type: Boolean, default: true } // 是否显示配送区域
});

const mapContainer = ref(null); // 定义 ref
let map = null;
let marker = null;
let infoWindow = null;
let districtPolygon = null;

// 计算属性：将分散经纬度转换为多边形路径
const districtPath = computed(() => {
  // 从分散属性中提取坐标点
  const points = [
    [props.point11, props.point12],
    [props.point21, props.point22],
    [props.point31, props.point32],
    [props.point41, props.point42],
    [props.point51, props.point52]
  ];

  // 过滤无效点（经度/纬度为0或相等的点）
  const validPoints = points.filter(
      (point) => point[0] !== 0 && point[1] !== 0 && point[0] !== point[1]
  );

  // 确保路径闭合
  return validPoints.length >= 3 ? [...validPoints, validPoints[0]] : [];
});

// 初始化地图
const initMap = () => {
  if (!mapContainer.value || !props.longitude || !props.latitude) {
    return;
  }

  window._AMapSecurityConfig = {
    securityJsCode: "716e782fa76f54ef41ddb8f59ee458f7",
  };

  AMapLoader.load({
    key: "f0510425d9c61c040a460360f6af7c20",
    version: "2.0",
    plugins: ["AMap.InfoWindow", "AMap.Scale","AMap.Polygon"] // 添加信息窗口插件
  })
      .then((AMap) => {
        // 创建地图实例
        map = new AMap.Map(mapContainer.value, {
          viewMode: "3D",
          zoom: 16,
          center: [props.longitude, props.latitude],
          pitch: 45 // 设置俯仰角增强3D效果
        });

        // // 添加地图控件
        // map.addControl(new AMap.Scale());
        // map.addControl(new AMap.ToolBar());

        createMarker(AMap);

        // 显示配送区域
        if (props.showDistrict && districtPath.value.length > 2) {
          createDistrictPolygon(AMap);
        }
      })
      .catch((e) => {
        console.error('地图加载失败:', e);
      });
};

// 创建标记点
const createMarker = (AMap) => {
  marker = new AMap.Marker({
    position: [props.longitude, props.latitude],
    title: props.siteName
  });

// 将标记添加到地图
  marker.setMap(map);

// 创建信息窗口
  infoWindow = new AMap.InfoWindow({
    content: `<div class="info-window-content">${props.siteName}</div>`,
    offset: new AMap.Pixel(0, -30)
  });

// 绑定标记点点击事件
  marker.on('click', () => {
    infoWindow.open(map, marker.getPosition());
  });
};

// 创建配送区域多边形
const createDistrictPolygon = (AMap) => {
  districtPolygon = new AMap.Polygon({
    path: districtPath.value,
    strokeColor: '#3498db',    // 蓝色边框
    strokeWeight: 2,
    strokeOpacity: 1,
    fillColor: '#3498db',      // 蓝色半透明填充
    fillOpacity: 0.1,
    zIndex: 10,
    bubble: true,
    strokeStyle: 'solid'
  });
  districtPolygon.setMap(map);
};

// 监听坐标变化
watch([() => props.longitude, () => props.latitude], () => {
  if (map && props.longitude && props.latitude) {
    map.setCenter([props.longitude, props.latitude]);
    marker?.setPosition([props.longitude, props.latitude]);
  }
});

// 监听区域数据变化
watch(districtPath, () => {
  if (districtPolygon) {
    districtPolygon.setMap(null);
    districtPolygon = null;
  }
  if (props.showDistrict && districtPath.value.length > 2) {
    createDistrictPolygon(window.AMap);
  }
});

onMounted(() => {
  initMap();
});


onUnmounted(() => {
  marker?.setMap(null);
  infoWindow?.close();
  districtPolygon?.setMap(null);
  map?.destroy();
  marker = null;
  infoWindow = null;
  districtPolygon = null;
  map = null;
});

</script>
<style scoped lang="scss">
#map_container{
  padding:0px;
  margin: 0px;
  width: 100%;
  height: 100%;
}
.info-window-content {
  padding: 10px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  font-size: 14px;
}
</style>